package com.ititer.web.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

import br.com.caelum.vraptor.InterceptionException;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.resource.ResourceMethod;

import com.ititer.annotation.LoginRequired;
import com.ititer.enums.PublicKeys;
import com.ititer.web.controller.Login;

@Intercepts
public class LoginCheckInterceptor implements Interceptor {

	@Autowired
	private final Result result = null;
	@Autowired
	private final HttpServletRequest request = null;

	@Override
	public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance)
			throws InterceptionException {
		LoginRequired loginRequired = method.getMethod().getAnnotation(LoginRequired.class);
		if (loginRequired != null) {
			Object currentUser = request.getSession().getAttribute(PublicKeys.CurrentUser.getValue());
			if (currentUser == null) {
				result.redirectTo(Login.class).form();
			}
		}
		stack.next(method, resourceInstance);
	}

	@Override
	public boolean accepts(ResourceMethod method) {
		return true;
	}

}
